package com.zscat.mallplus.dms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.dms.service.IDeviceService;
import com.zscat.mallplus.qsg.QsgDevice;
import com.zscat.mallplus.qsg.impl.WechatApiService;
import com.zscat.mallplus.qsg.mapper.QsgDeviceMapper;
import com.zscat.mallplus.sys.mapper.SysAppletSetMapper;
import com.zscat.mallplus.ums.entity.SysAppletSet;
import com.zscat.mallplus.utils.OssUtil;
import com.zscat.mallplus.utils.WXQRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;

@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<QsgDeviceMapper, QsgDevice> implements IDeviceService {


    @Resource
    private SysAppletSetMapper appletSetMapper;

    @Resource
    private WechatApiService wechatApiService;

    @Value("${qrcode.img.dir}")
    private String qrCodeDir;

    @Override
    public String generateDeviceQRCodeById(Long deviceId) {
        SysAppletSet appletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        FileOutputStream outStream = null;
        InputStream inputStream = null;
        String path = qrCodeDir + "device_" + deviceId + ".png";
        try {
            String token = wechatApiService.getAccessToken(appletSet.getAppid(),appletSet.getAppsecret());
            log.info("微信token:{}", token);
            byte[] result = WXQRCodeUtil.getDeviceQRCodeById(deviceId, token);
            File imageFile = new File(path);
            if (!imageFile.exists()) {
                imageFile.createNewFile();
            }
            //创建输出流
            outStream = new FileOutputStream(imageFile);
            inputStream = new ByteArrayInputStream(result);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outStream.write(buf, 0, len);
            }
            outStream.flush();
            //写入数据
            File file = new File(path);
            String url = OssUtil.uploadLocalFile(file, OssUtil.FileDirType.ARTICLE_IMAGES);
            log.info("上传结果:{}", url);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成设备:{}小程序码失败.异常:{}", deviceId, e.getMessage());
        } finally {
            try {
                //关闭输出流
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
